package com.yunpeng.aidevice.common.controllers.users;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunpeng.aidevice.biz.service.IDeviceBizService;
import com.yunpeng.aidevice.biz.service.IUserBizService;
import com.yunpeng.aidevice.biz.service.IUserLoginBizService;
import com.yunpeng.aidevice.common.constant.ConfigConstantValues;
import com.yunpeng.aidevice.common.dto.cache.LoginUserCacheDTO;
import com.yunpeng.aidevice.common.dto.query.UserQueryDTO;
import com.yunpeng.aidevice.common.dto.save.UserSaveDTO;
import com.yunpeng.aidevice.common.enums.ResultCodeEnum;
import com.yunpeng.aidevice.common.vo.SimpleEntityVO;
import com.yunpeng.aidevice.common.vo.device.DeviceAppDetailVO;
import com.yunpeng.aidevice.common.vo.user.UserBasicInfoVO;
import com.yunpeng.aidevice.permission.service.IPermissionOuterService;
import com.yunpeng.common.dto.Result;
import com.yunpeng.common.paging.PagingQueryDTO;
import com.yunpeng.common.util.ParametersCheckUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * UserController
 *
 * @author : Moore(hemw)
 * @date : 2020-04-13
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private IUserBizService userBizService;

    @Resource
    private IUserLoginBizService userLoginBizService;

    @Resource
    private IPermissionOuterService permissionOuterService;

    @Resource
    private IDeviceBizService deviceBizService;

    /**
     * 新增用户
     *
     * @param userSaveDTO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addNew", method = RequestMethod.POST)
    public Result<Void> addNew(@RequestBody UserSaveDTO userSaveDTO) {
        ParametersCheckUtil.isNotNull(userSaveDTO, "没有传递任何参数");
        ParametersCheckUtil.isNotBlank(userSaveDTO.getPhone(), "用户电话为空");
        ParametersCheckUtil.isNotBlank(userSaveDTO.getUserNumber(), "用户编号为空");
        ParametersCheckUtil.isNotBlank(userSaveDTO.getUserName(), "用户名称为空");
        ParametersCheckUtil.isNotBlank(userSaveDTO.getEmail(), "用户邮箱为空");
        ParametersCheckUtil.isNotNull(userSaveDTO.getInvalidDate(), "用户失效时间为空");
        ParametersCheckUtil.hasOneNotBlank(userSaveDTO.getOrgCode(), userSaveDTO.getOrgNumber(), "用户组织信息为空");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        userSaveDTO.setMerchantCode(loginUserCacheDTO.getMerchantCode());
        userSaveDTO.setTenantCode(loginUserCacheDTO.getTenantCode());
        return userBizService.addNewUser(userSaveDTO, loginUserCacheDTO.getCode());
    }

    /**
     * 获取登录用户的基础信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getLoginUserBasicInfo", method = RequestMethod.POST)
    public Result<UserBasicInfoVO> getLoginUserBasicInfo() {
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        return userBizService.getUserBasicInfo(loginUserCacheDTO.getCode(), loginUserCacheDTO.getMerchantCode());
    }


    /**
     * 修改用户信息
     *
     * @param userSaveDTO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateUserInfo", method = RequestMethod.POST)
    public Result<Void> updateUserInfo(@RequestBody UserSaveDTO userSaveDTO) {
        ParametersCheckUtil.isNotNull(userSaveDTO, "没有传递任何参数");
        ParametersCheckUtil.isNotBlank(userSaveDTO.getPhone(), "用户电话为空");
        ParametersCheckUtil.isNotBlank(userSaveDTO.getUserNumber(), "用户编号为空");
        ParametersCheckUtil.isNotBlank(userSaveDTO.getUserName(), "用户名称为空");
        ParametersCheckUtil.isNotBlank(userSaveDTO.getEmail(), "用户邮箱为空");
        ParametersCheckUtil.isNotNull(userSaveDTO.getInvalidDate(), "用户失效时间为空");
        ParametersCheckUtil.hasOneNotBlank(userSaveDTO.getOrgCode(), userSaveDTO.getOrgNumber(), "用户组织信息为空");
        permissionOuterService.clearUserCache(userSaveDTO.getUserCode());
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        userSaveDTO.setMerchantCode(loginUserCacheDTO.getMerchantCode());
        userSaveDTO.setTenantCode(loginUserCacheDTO.getTenantCode());
        //验证更新用户信息权限
        //if (permissionOuterService.checkUpdateAnotherUserInfo(userSaveDTO.getUserCode(), ConfigConstantValues.getLoginUserCacheDTO().getCode())) {
        return userBizService.updateUserBasicInfo(userSaveDTO, loginUserCacheDTO.getCode());
        // }
        // return Result.fail(ResultCodeEnum.HAS_NOT_PERMISSION);
    }

    /**
     * 更新用户绑定组织信息
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "usersBindOrganization", method = RequestMethod.POST)
    public Result<Void> usersBindOrganization(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String organizationCode = requestParam.getString("organizationCode");
        JSONArray userArray = requestParam.getJSONArray("userCodes");
        ParametersCheckUtil.collectionIsNotNullOrderEmpty(userArray, "无效的用户代码数组");
        ParametersCheckUtil.isNotBlank(organizationCode, "无效的组织代码");
        List<String> userCodes = userArray.toJavaList(String.class);
        permissionOuterService.clearUsersCache(userCodes);
        return userBizService.usersBindOrganization(userCodes, organizationCode, ConfigConstantValues.getLoginUserCacheDTO().getCode(), ConfigConstantValues.getLoginUserCacheDTO().getMerchantCode());
    }

    /**
     * 获取用户的基础信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "detail", method = RequestMethod.POST)
    public Result<UserBasicInfoVO> detail(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String userCode = requestParam.getString("userCode");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        return userBizService.getUserBasicInfo(userCode, loginUserCacheDTO.getMerchantCode());
    }


    /**
     * 商户端的用户列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public Result<PagingQueryDTO> list(@RequestBody UserQueryDTO userQueryDTO) {
        ParametersCheckUtil.isNotNull(userQueryDTO, "没有传递任何参数");
        ParametersCheckUtil.isNotNull(userQueryDTO.getPageSize(), "需要传入页数量");
        ParametersCheckUtil.isNotNull(userQueryDTO.getCurrentPage(), "需要传入页码");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        userQueryDTO.setMerchantCode(loginUserCacheDTO.getMerchantCode());
        userQueryDTO.setTenantCode(loginUserCacheDTO.getTenantCode());
        return userBizService.queryUserList(userQueryDTO);
    }

    /**
     * 启用用户
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public Result<Void> enable(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String userCode = requestParam.getString("userCode");
        ParametersCheckUtil.isNotBlank(userCode, "无效的用户代码");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        return userBizService.enableOrDisableUser(true, userCode, loginUserCacheDTO.getMerchantCode(), loginUserCacheDTO.getTenantCode(), loginUserCacheDTO.getCode());
    }

    /**
     * 禁用用户
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public Result<Void> disable(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String userCode = requestParam.getString("userCode");
        ParametersCheckUtil.isNotBlank(userCode, "无效的用户代码");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        return userBizService.enableOrDisableUser(false, userCode, loginUserCacheDTO.getMerchantCode(), loginUserCacheDTO.getTenantCode(), loginUserCacheDTO.getCode());
    }

    /**
     * 用户下拉数据
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "dropDownList", method = RequestMethod.POST)
    public Result<List<SimpleEntityVO>> dropDownList(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String merchantCode = requestParam.getString("merchantCode");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        if (StringUtils.isBlank(merchantCode)) {
            merchantCode = loginUserCacheDTO.getMerchantCode();
        }
        return userBizService.dropDownList(merchantCode, loginUserCacheDTO.getTenantCode());
    }

    /**
     * 设备详情数据（提供给app）
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deviceMerchantUserList", method = RequestMethod.POST)
    public Result<DeviceAppDetailVO> deviceMerchantUserList(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String deviceId = requestParam.getString("deviceId");
        return deviceBizService.getDetail4App(deviceId);
    }


    /**
     * 删除用户
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public Result<Void> remove(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        String userCode = requestParam.getString("userCode");
        ParametersCheckUtil.isNotBlank(userCode, "无效的用户代码");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        return userBizService.removeUser(userCode, loginUserCacheDTO.getMerchantCode(), loginUserCacheDTO.getTenantCode());
    }

    /**
     * 更新密码
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updatePassword", method = RequestMethod.POST)
    public Result<Void> updatePassword(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        String userCode = requestParam.getString("userCode");
        String historyPassword = requestParam.getString("currentPassword");
        String password = requestParam.getString("newPassword");
        if (userCode == null) {
            userCode = loginUserCacheDTO.getCode();
        }
        ParametersCheckUtil.isNotBlank(historyPassword, "无效的当前密码");
        ParametersCheckUtil.isNotBlank(password, "无效的新密码");
        Result<Void> result = userBizService.updatePassword(userCode, historyPassword, password);
        if (result.isSuccess()) {
            try {
                //强制重新登录
                userLoginBizService.unLogin(loginUserCacheDTO);
            } catch (Exception ignored) {
            }
        }
        return result;
    }

    /**
     * 更新密码
     *
     * @param requestParam
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "resetPassword", method = RequestMethod.POST)
    public Result<Void> resetPassword(@RequestBody JSONObject requestParam) {
        ParametersCheckUtil.mapIsNotNullOrderEmpty(requestParam, "没有传递任何参数");
        LoginUserCacheDTO loginUserCacheDTO = ConfigConstantValues.getLoginUserCacheDTO();
        if (!loginUserCacheDTO.getMerchantDefaultUser()) {
            return Result.fail(ResultCodeEnum.HAS_NOT_PERMISSION);
        }
        String userCode = requestParam.getString("userCode");
        Result<Void> result = userBizService.resetPassword(userCode, loginUserCacheDTO.getMerchantCode());
        if (result.isSuccess()) {
            try {
                //强制重新登录
                userLoginBizService.unLogin(loginUserCacheDTO);
            } catch (Exception ignored) {
            }
        }
        return result;
    }
}
